import React, {Component} from 'react';
import {Image, Text, TouchableOpacity, View, StyleSheet, TextInput, Alert, AsyncStorage} from 'react-native';
import {SegmentedControls} from 'react-native-radio-buttons';
import {NavigationActions} from 'react-navigation';
import Toast from '@remobile/react-native-toast';
import WebIM from './../utils/Lib/WebIM';
import FetchUtils from './../utils/FetchUtils';
import utils from './../utils/utils';
import Spinner from "react-native-loading-spinner-overlay";

export default class LoginPage extends Component {
    constructor(props) {
        super(props);
        this.loginParam = {
            username: '',
            password: '',
            role: '',
        };
        this.HXToken = "";
        this.state = {
            options: ["体验官", "搭配师"],
            loginButStatus: false,
            loadingStatus: false,
        };
    }

    /*选择登陆角色*/
    setSelectedOption(selectedOption) {
        this.loginParam.role = selectedOption;
    }

    /*登陆按钮,防止多次点击*/
    loginBut = async () => {
        if (!this.state.loginButStatus) {
            await this.setState({loginButStatus: true,})
            setTimeout(async () => {
                await this.setState({loginButStatus: false})
            }, 1500);


            if (this.loginParam.username == '') {
                Alert.alert("警告", "请输入用户名")
            } else if (this.loginParam.password == '') {
                Alert.alert("警告", "请输入密码")
            } else if (this.loginParam.role == '') {
                Alert.alert("警告", "请选择角色")
            } else {
                this.setState({
                    loadingStatus: true,
                });
                await FetchUtils.postWithParams(utils.apiUrl + '/user/login', JSON.stringify(this.loginParam), (res) => {
                    if (res.code == 200) {
                        AsyncStorage.setItem("XToken", res.apiData.XToken, (error) => {
                            if (error) {
                                console.log('存值失败:', error);
                            } else {
                                AsyncStorage.setItem("role", res.apiData.role, (error) => {
                                    if (error) {
                                        console.log('存值失败:', error);
                                    } else {
                                        AsyncStorage.setItem("username", res.apiData.username, (error) => {
                                            if (error) {
                                                console.log('存值失败:', error);
                                            } else {
                                                AsyncStorage.setItem("userId", res.apiData.userId, (error) => {
                                                    if (error) {
                                                        console.log("存值失败:", error)
                                                    } else {
                                                        AsyncStorage.setItem("avatar", res.apiData.avatar, (error) => {
                                                            if (error) {
                                                                console.log("存值失败:", error)
                                                            } else {
                                                                console.log('存值成功!');
                                                                console.log(res);
                                                                this._registerHXListener();
                                                                this._loginToHX(this.loginParam.username);
                                                            }
                                                        })
                                                    }
                                                })
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    } else {
                        this.setState({
                            loadingStatus: false,
                        });
                        Alert.alert("警告", res.apiData);
                    }
                });
            }
        } else {
            Alert.alert("警告", "点击频繁")
        }
    };

    // 注册环信的消息监听器
    _registerHXListener() {
        WebIM.conn.listen({
            // xmpp连接成功
            onOpened: (msg) => {
                console.log(msg);
                if (msg.accessToken) {
                    AsyncStorage.setItem("HXToken", msg.accessToken, (error) => {
                        if (error) {
                            console.log("存值失败" + error)
                        } else {
                            console.log("存值成功");
                            this.setState({
                                loadingStatus: false,
                            });
                            const resetAction = NavigationActions.reset({
                                index: 0,
                                actions: [
                                    NavigationActions.navigate({routeName: 'MainTabNav'})
                                ]
                            });
                            this.props.navigation.dispatch(resetAction);
                        }
                    })
                }
            },
            onError: (error) => {
                console.log(error)
            },
        });
    }

    // 登录环信聊天服务器
    _loginToHX = (username) => {
        if (WebIM.conn.isOpened()) {
            WebIM.conn.close('logout');
        }
        // 下面调用成功后，会回调注册的listener
        WebIM.conn.open({
            apiUrl: WebIM.config.apiURL,
            user: username,
            pwd: username,
            appKey: WebIM.config.appkey,
            success: function (token) {
                console.log("登录成功")
            },
            error: function () {
                console.log('登录聊天服务器出错');
            }
        });
    };

    render() {

        return (
            <View style={styles.pageView}>
                <View><Image source={require('../../img/yi_jia3x.png')} style={styles.imgTop}/></View>
                <Spinner visible={this.state.loadingStatus} textContent={""} textStyle={{color: '#FFF'}}/>
                <View style={styles.inputView}>
                    <TextInput onChangeText={
                        (text) => {
                            this.loginParam.username = text;
                        }
                    }
                               style={styles.viewTextInputUp} placeholder="用户名"
                               underlineColorAndroid={'transparent'}></TextInput>
                    <TextInput onChangeText={
                        (text) => {
                            this.loginParam.password = text;
                        }
                    } style={styles.viewTextInputBottom} placeholder="密码" secureTextEntry={true}
                               underlineColorAndroid={'transparent'}></TextInput></View>

                <View></View>

                <SegmentedControls
                    containerBorderRadius={0}
                    tint={'#000'}
                    selectedTint={'white'}
                    backTint={'#FFF'}
                    options={this.state.options}
                    allowFontScaling={false} // default: true
                    onSelection={this.setSelectedOption.bind(this)}
                    selectedOption={this.state.selectedOption}
                    optionStyle={{fontFamily: 'AvenirNext-Medium'}}
                    containerStyle={[styles.typeTouchView, {width: utils.autoWidth(320)}]}
                />

                <TouchableOpacity style={styles.loginTouch} onPress={this.loginBut}>
                    <View style={styles.loginTouchTextView}><Text style={styles.loginTouchText}>登录</Text>
                        <Text style={styles.loginTouchText}>SIGN IN</Text>
                    </View>
                </TouchableOpacity>

            </View>
        );
    }
};

const styles = StyleSheet.create({
    pageView: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#FFFFFF',
    },
    imgTop: {
        width: utils.autoWidth(180),
        height: utils.autoheight(140),
        marginTop: utils.autoheight(70),
    },
    inputView: {
        marginTop: utils.autoheight(40.5),
    },
    viewTextInputUp: {
        width: utils.autoWidth(320),
        height: utils.autoheight(44),
        borderColor: '#A0A0A0',
        borderTopWidth: utils.autoWidth(0.5),
        borderRightWidth: utils.autoWidth(0.5),
        borderLeftWidth: utils.autoWidth(0.5),
    },
    viewTextInputBottom: {
        width: utils.autoWidth(320),
        height: utils.autoheight(44),
        borderColor: '#A0A0A0',
        borderTopWidth: utils.autoWidth(0.5),
        borderRightWidth: utils.autoWidth(0.5),
        borderBottomWidth: utils.autoWidth(0.5),
        borderLeftWidth: utils.autoWidth(0.5),
    },
    typeTouchView: {
        flexDirection: 'row',
        justifyContent: 'center',
        marginTop: utils.autoheight(40.5),
        borderWidth: 1,
        borderColor: '#000',
    },
    typeTouchLeft: {
        borderColor: '#010101',
        borderWidth: utils.autoWidth(1),
        borderRightWidth: utils.autoWidth(0.5),
        width: utils.autoWidth(160),
        height: utils.autoheight(29),
        alignItems: 'center',
    },
    typeTouchRight: {
        borderColor: '#010101',
        borderWidth: utils.autoWidth(1),
        borderLeftWidth: utils.autoWidth(0.5),
        width: utils.autoWidth(160),
        height: utils.autoheight(29),
        alignItems: 'center',
    },
    loginTouch: {
        width: utils.autoWidth(320),
        height: utils.autoheight(50),
        borderColor: '#010101',
        borderWidth: utils.autoWidth(2),
        alignItems: 'center',
        marginTop: utils.autoheight(40.5),
    },
    loginTouchTextView: {
        alignItems: 'center',
    },
    loginTouchText: {
        fontSize: utils.setSpText(17),
        color: '#010101',
    }
})
